<template>
	<div>
		<head-top></head-top>
		<div class="boxWrap">			
			<div class="createTemplate clearfix">
				<div class="alert alert-success text-center" v-if="saveSuccess" style="background-color: #dff0d8;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>成功！</strong>操作成功。
				</div>
				<div class="alert alert-danger text-center" v-if="saveError" style="background-color: #f2dede;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>{{errorTip}}！</strong>
				</div>
				<div class="left createTemplate_left">
					<div style="margin-bottom:50px;">
						<p class="createTemplate_words text-left">读取类型</p>
						<p class="read_type">
							<span v-for='(data,key,index) in readTypes' v-on:click="addClassFun(index)" v-bind:class='{read_type_style:index==addClassIndex}'>{{data.data}}</span>
						</p>
					</div>
					<div class="clearfix">
						<span class="createTemplate_words left">输入变量列表</span>
						<label class="right createTemplate_words" style="font-weight:normal;">				
					        <input class="input_radio" type="checkbox" name="dash_checkbox" @change="changeHeaderState($refs.this)" ref="this">
					        <span class="input_checkbox input_radioInput"></span>含有标签
						</label>
					</div>
					<div class="contain_tags text-left" v-if="containTags">
						<input type="text" placeholder="标签名" class="contain_input"/>
						<select name="">
							<option value="0">Str</option>
							<option value="0">Int</option>
							<option value="0">Float</option>
						</select>
					</div>
					<div class="clearfix" style="margin-top:20px;">
						<span class="createTemplate_words left" @click="test()">其他特征</span>
						<span class="createTemplate_words right cursor" @click="addFeaturesItem()">加</span>
					</div>
					<!--添加其他特征-->
					<div class="text-left" id="AddText">
						<input type="text"  value="" class="contain_input" is="feature_item" v-for="(todo, index) in features"/>	
					</div>
					<div class="clearfix" style="margin-top:20px;">
						<span class="createTemplate_words left">模版参数列表</span>
						<span class="createTemplate_words right cursor" @click="addParameterItem(1)">加</span>
					</div>
					<!--添加模板参数-->
					<div class="text-left properties">
						<table>
							<tr>
	                            <th>名称</th>
	                            <th>类型</th>
	                            <th>默认值</th>
	                        </tr>
				        	<tr v-for="item in parameterArr">
					            <td>{{item.name}}</td>
					            <td>{{item.selected}}</td> 
					            <td>{{item.default}}</td>
					        </tr>
					    </table>
					</div>
					<div class="clearfix" style="margin-top:20px;">
						<span class="createTemplate_words left">模型超参数列表</span>
						<span class="createTemplate_words right cursor" @click="addParameterItem(2)">加</span>
					</div>
					<table>
						<tr>
                            <th>名称</th>
                            <th>类型</th>
                            <th>默认值</th>
                        </tr>
				        <tr v-for="item in hyperParameterArr">
				            <td>{{item.name}}</td>
				            <td>{{item.selected}}</td> 
				            <td>{{item.default}}</td>
				        </tr>
				    </table>
				</div>
				<div class="left online_editor">
					<div class="clearfix editor_operation" >
						<h3 class="left detail_title">在线编辑</h3>
						<button class="right btn" disabled="disabled">notebook</button>
						<button class="right btn" disabled="disabled">发布</button>
						<button class="right btn saveTemBtn" @click="showSave()">保存</button>
						<button class="right btn testTemBtn" @click="testTemplate()">测试</button>
					</div>
					<p>
<pre id="code" class="ace_editor" style="min-height:400px;width:918px;"><textarea class="ace_text-input"></textarea></pre>				
					</p>
					<div class="operation_result">
						<p class="text-left">运行结果</p>
						<p class="text-left p_words" style="width:100%;">
							Plantronics with its GN Netcom wireless headset cPlantronics with its GN Netcom wireless headset c
							onics with its GN Netcom wire
						</p>
					</div>			
				</div>
			</div>
		</div>
		<footerHtml></footerHtml>
		<div id="mask" v-if="seen"></div>
		<div class="bomb_box bomb_setting_parameters" v-if="seenSet">
			<p>设置参数</p>
			<p class="text-left">
				<span class="data_info_name">名称</span>
				<input type="text" class="setting_parameters_val" v-model="fillInName"/>
			</p>			
			<p class="text-left">
				<span class="data_info_name">类型</span>
				<select name="" v-model="selected">
        			<option v-for="option in options" v-bind:value="option.value">{{ option.text }}</option>	            		
        	</select >
			</p>			
			<!--如果是number-->
			<div v-if="selected==1">
				<p class="text-left ">
					<span class="data_info_name">默认</span>
					<input type="number" class="setting_parameters_val" v-model="fillInDefault"/>
				</p>
				<p class="text-left">
					<span class="data_info_name">最小</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMin"/>
				</p>
				<p class="text-left ">
					<span class="data_info_name">最大</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMax"/>
				</p>
			</div>
			<!--如果是boolean-->
			<div v-else-if="selected==2" class="text-left">
				<label class="input_label">
			        <input class="input_radio setting_parameters_val" type="radio" name="param_checkbox_selsect" @click="changeFillDefaultT()">		
			        <span class="input_checkbox input_radioInput"></span>true
				</label>
				<label class="input_label">
			        <input class="input_radio setting_parameters_val" type="radio" name="param_checkbox_selsect" @click="changeFillDefaultF()">
			        <span class="input_checkbox input_radioInput"></span>false
				</label>
			</div>
			<!--如果是string-->
			<div  v-else>
				<p class="text-left ">
					<span class="data_info_name">默认</span>
					<input type="text" class="setting_parameters_val" v-model="fillInDefault"/>
				</p>
				<p class="text-left ">
					<span class="data_info_name">范围</span>
					<input type="text" class="setting_parameters_val"  v-model="fillInRange" placeholder="范围之间请用逗号连接"/>
				</p>
			</div>			
			<p  class="text-right">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="data_info_sure btn" @click="synchronization()">确定</button>
			</p>
		</div>	
		<!--创建模板的弹框-->
		<div class="bomb_box" v-if="showSaveTem">
			<p>创建模板</p>
			<p class="data_info_tip" v-if="seenTemTip" style="font-size: 12px;color: #FF5D30;letter-spacing: 0.79px;">请检查填写信息!</p>
			<p class="text-left">
				<span class="data_info_name">模板名称</span>
				<input type="text" class="data_info_name_val editTitle" v-model="inputTemName"/>
			</p>
			<p class="text-left">
				<span class="data_info_name" style="display: block; float: left;">模板描述</span>
				<textarea name="des" class="data_info_des_val editDes" v-model="inputTemDes"></textarea>
			</p>
			<p class="text-left">
				<span class="data_info_name">隐私性</span>
				<span class="cursor data_info_public change_visible" data_visible="0" @click="changeVisible0()" 
					style="margin-left: 12px;padding:6px 26px;border-radius:2px;">公开</span>
				<span class="cursor data_info_private" data_visible="1" @click="changeVisible1()" 
					style="padding:6px 26px;margin-left:20px;border-radius:2px;">私有</span>
			</p>
			<p  class="text-right" style="margin-top:40px;">
				<button class="btn data_info_cancel" @click="bombBoxHide()">取消</button>
				<button class="btn data_edit_sure" @click="SaveTemplate()" style="margin-left:40px;">确定</button>
			</p>
		</div>
	</div>
	
</template>

<script>
import Vue from 'vue'	
import { bus } from '../assets/js/bus.js'
//引入公共模块
import headTop from '@/components/headTop'
import editor from '@/components/editor'
import footerHtml from '@/components/footerHtml'

//api	
import {urlSaveTemplate,urlTestTemplate,urlGetDetail} from '../api/api'

Vue.component('feature_item', {
    template: `<input type="text"  value="" class="contain_input" />` 
})

export default {		
    name: 'createTemplate', 
    data(){
    	return {
    		templateId:'',
    		headerState:0, 
    		editVis:0,
    		containTags:false,
    		seen:false,
    		seenSet:false,
    		typeNumber:false,
    		typeOther:true,
    		saveSuccess:false,
    		saveError:false,
    		showSaveTem:false,
    		seenTemTip:false,
    		errorTip:'',
    		path:'',
			fillInName:'',
			fillInDefault:'',
			fillInMax:'',
			fillInMin:'',
			fillInRange:'',
			inputTemName:'',
			inputTemDes:'',
			hyperParameterArr:[],
			parameterArr:[],
			hyper_param_spec:{},
			param_spec:{},
			addCode:'',
    		features: [
                '+添加'
           	],
           	sv:'+添加',
           	readTypes: {  
				data1: {  
					data: "Excel"
				},  
				data2: {  
					data: "CSV"
				}
			},
			addClassIndex:0,	
			selected: '0',
		   	options: [
			   	{ text: 'string', value: '0' },
			    { text: 'number', value: '1' },
			    { text: 'boolean', value: '2' }
		   	]
	
    	}
    },
    components:{
    	headTop,
    	editor,
    	footerHtml
    },   
    mounted(){ 	
    	let editor = ace.edit("code");
        let theme = "clouds",
            language = "c_cpp";
        editor.setTheme("ace/theme/" + theme);
        editor.session.setMode("ace/mode/" + language);       
        editor.setFontSize(16);
        editor.setReadOnly(false); 
        editor.setOption("wrap", "free")
        ace.require("ace/ext/language_tools");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
		//获取之前编辑的代码以及参数
		let sendData={
			id:this.$route.params.id
		}
		urlGetDetail(sendData).then(response => {
  			if(response.data.code==200){	
  				this.addCode=response.data.data.code;
  				editor.setValue(this.addCode);
  				//设置的参数展示
  				let resDataJson=eval('('+response.data.data.param_spec+')'),			  				
			  		resProperties=JSON.stringify(resDataJson.properties),
			  		resProperties2=JSON.parse(resProperties)
  				console.log(resProperties2)
  				let self=this;
  				$.each(resProperties2, function(key,val) {
				    self.parameterArr.push({
						name:key,
						selected:val.type,
						default:val.default
					})	
				});
				//设置的超参数展示
				let resDataJsonHyper=eval('('+response.data.data.hyper_param_spec+')'),			  				
			  		resPropertiesHyper=JSON.stringify(resDataJsonHyper.properties),
			  		resPropertiesHyper2=JSON.parse(resPropertiesHyper)
  				console.log(resPropertiesHyper2)
  				let selfHyper=this;
  				$.each(resPropertiesHyper2, function(key,val) {
				    selfHyper.hyperParameterArr.push({
						name:key,
						selected:val.type,
						default:val.default
					})	
				});
  			}else if(response.data.code!=200){
  				console.log('获取数据失败')
  			}				    		
     	});
    },
    methods: {
    	changeVisible0(){
    		$('.data_info_public').addClass('change_visible');
    		this.editVis=0;
    		$('.data_info_private').removeClass('change_visible');
    	},
    	changeVisible1(){
    		$('.data_info_private').addClass('change_visible');
    		this.editVis=1;
    		$('.data_info_public').removeClass('change_visible');
    	},
    	changeFillDefaultT(){
    		this.fillInDefault='true';
    	},
    	changeFillDefaultF(){
    		this.fillInDefault='false';
    	},
    	bombBoxHide(){
    		this.seen=false;
			this.seenSet=false;
			this.showSaveTem=false;
    	},
		codeCheckout(){
			console.log(this.inputCode=ace.edit("code").getValue())
		},
		changeHeaderState(filter){
			if($(filter).is(":checked")){ 
				this.headerState=1;
				this.containTags=true;
          	}else{
          		this.headerState=0;
          		this.containTags=false;
          	}
		},
		addFeaturesItem(){
			this.features.push(this.sv)
		},
		addParameterItem(path){
			this.seen=true;
			this.seenSet=true;
			this.path=path;
		},
		addClassFun: function(index) {  
			console.log(this.addClassIndex)
			this.addClassIndex = index;  
		},		
		synchronization(){	
//			$('.saveTemBtn,.testTemBtn').removeAttr('disabled');
			this.seen=false;
			this.seenSet=false;
			if(this.path==1){
				//设置参数
				this.parameterArr.push({
					//自己定义
					name:this.fillInName,
					selected:this.selected,
					default:this.fillInDefault
				})
				//拼装成这种格式：{"type":"object","properties":{ "KEY1":{"type":"string","enum":["1"],"default":"1"},"KEY2"{"type":"number","minimum":"1","maximum":"10","default":"1"}}}
				this.param_spec['type'] = 'object';
				if(typeof(this.param_spec['properties']) == 'undefined'){
					this.param_spec['properties']= {};
				}
				var btnType =this.selected;
				switch(btnType){
					case '0'://字符串
						var data = {};
						data['type'] = 'string';
						data['enum'] = this.fillInRange.split(",");
						data['default'] = this.fillInDefault;
						this.param_spec['properties'][this.fillInName]=data;
						break;
					case '1'://整型
						var data = {};
						data['type'] = 'number';
						data['minimum'] = (Number(this.fillInMin));
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.param_spec['properties'][this.fillInName]=data;
						break;
					case '2'://boolean
						var data = {};
						data['type'] = 'boolean';
						data['default'] = eval(this.fillInDefault.toLowerCase());
						this.param_spec['properties'][this.fillInName]=data;
						break;
				}
			}else if(this.path==2){				
				//设置超参数点击同步到左边
				this.hyperParameterArr.push({
					//自己定义
					name:this.fillInName,
					selected:this.selected,
					default:this.fillInDefault
				})
				this.hyper_param_spec['type'] = 'object';
				if(typeof(this.hyper_param_spec['properties']) == 'undefined'){
					this.hyper_param_spec['properties']= {};
				}
				var btnType =this.selected;
				switch(btnType){
					case '0'://字符串
						var data = {};
						data['type'] = 'string';
						data['enum'] = this.fillInRange.split(",");
						data['default'] = this.fillInDefault;
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
					case '1'://整型
						var data = {};
						data['type'] = 'number';
						data['minimum'] = (Number(this.fillInMin)) ;
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
					case '2'://bool
						var data = {};
						data['type'] = 'boolean';
						data['default'] = eval(this.fillInDefault.toLowerCase());
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
				}
			}
		},
		showSave(){
			this.seen=true;
			this.showSaveTem=true;
		},
		SaveTemplate(){
			this.seen=false;
			this.showSaveTem=false;			
	    	let sendData={   		
		  		name:this.inputTemName,
		  		description:this.inputTemDes,
		  		visible:this.editVis,
				type:0,			
				content:this.inputCode=ace.edit("code").getValue(),			
				param_spec:JSON.stringify(this.param_spec),	
				hyper_param_spec:JSON.stringify(this.hyper_param_spec)			  		
	    	};
	    	console.log(sendData);
//	    	return false;
			if(this.inputTemName=='' || this.inputTemDes==''){
				this.seenTemTip=true;
			}else{
				this.seenTemTip=false;
		    	urlSaveTemplate(sendData).then(response => {
		  			if(response.data.code==200){
		  				this.saveSuccess=true;
		  				this.templateId=response.data.data.template_id;
		  				let self=this;
	     				setTimeout(function(){
	     					self.$router.push({name:"templateDetail",params:{id:self.templateId}});	
	     				}, 2000);
		  			}else if(response.data.code==201){	
		  				this.errorTip=response.data.message;
		  				this.saveError=true;
		  			}				    		
	     		});
			}
		},
		testTemplate(){
	    	let sendData={   		
		  		name:this.inputTemName,
		  		description:this.inputTemDes,
		  		visible:this.editVis,
				type:0,			
				content:this.inputCode=ace.edit("code").getValue(),			
				param_spec:JSON.stringify(this.param_spec)	,	
				hyper_param_spec:JSON.stringify(this.hyper_param_spec)			  		
	    	};
	    	urlTestTemplate(sendData).then(response => {
	  			if(response.data.code==200){	  				
					alert('测试ok')
	  			}else if(response.data.code!=200){
	  				console.log('获取数据失败')
	  			}				    		
     		});
		},
		
		
		
  	}
}
</script>


<style lang="css">
	@import "../assets/css/base.css"
</style>
<style lang="css">
	@import "../assets/css/createTemplate.css"
</style>
<style lang="css">
	@import "../assets/css/data_info.css"
</style>